<?php
/**
 * projectname:gdu_cms2 
 * author:senman
 * time:2017/8/9 13:13
 */

namespace app\admin\controller;

use app\admin\builder\AdminAccessBuilder;
use app\common\model\Group;
use think\Request;
use think\Session;


class Auth extends Base
{

    protected $rule_model;
    protected $user_model;
    protected $group_model;
    protected $access_model;
    protected $user_id;
    protected $no_action_time;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->rule_model = model('Rule');
        $this->group_model = model('Group');
        $this->user_model = model('User');
        $this->access_model = model('Access');
        $this->user_id = session('user_id');
        $this->no_action_time = config('auth.no_action_time');
    }

    /**
     * 权限认证
     */
    protected function auth(array $name = null)
    {
        $this->user_id = session('user_id');

        if (cookie('gatway_key') != md5($this->user_id)) {
            //清除session
            //写日志
            Log::writeLog("长时间未操作系统退出");
            Session::clear();
            return $this->send(0, '请先登陆', url('admin/Auth/login'));
        }

        if (!$this->user_id > 0) {
            return $this->send(0, '请先登陆', url('admin/Auth/login'));
        }

        //获取该用户信息
        $user_info = $this->user_model->where(['id' => $this->user_id])->field('status')->find();
        if ($user_info['status'] != 0) {
            return $this->send(0, '账户已被禁用', url('admin/auth/login'));
        }

        if (!$this->check($name)) {
            return $this->send(0, '权限不足');
        }

        cookie('gatway_key', md5($this->user_id), $this->no_action_time);
    }

    /**
     * @describe 检查权限
     * @param array|null $name
     * @return bool
     */
    public function check($name = null)
    {
        $admin_id_arr = @explode(",", config('auth.administrator'));
        if (in_array($this->user_id, $admin_id_arr)) {
            return true;
        }
        if ($name == null) {
            $model = $this->request->module();
            $controller = $this->request->controller();
            $action = $this->request->action();
            $url = strtolower($model . "/" . $controller . "/" . $action);
            if (in_array($url, config('auth.except'))) {
                return true;
            } else {
                $condition = [];
                $condition['url'] = $url;
                $condition['status'] = 0;
                $rule = $this->rule_model->where($condition)->field('id')->find();
                if ($rule) {
                    if (in_array($rule['id'], $this->getAuthOfUser())) {
                        return true;
                    }
                }

            }

        } else {
            $condition = [];
            $condition['url'] = $name;
            $condition['status'] = 0;
            $rule = $this->rule_model->where($condition)->field('id')->find();
            if ($rule) {
                if (in_array($rule['id'], $this->getAuthOfUser())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @describe 获取该用户的所有权限
     * @return array
     */
    public function getAuthOfUser()
    {
        $auth_list = session('auth_list');
        if (!$auth_list) {
            $user_id = $this->user_id;
            $auth_list = [];
            $admin_id_arr = @explode(",", config('auth.administrator'));
            if (in_array($this->user_id, $admin_id_arr)) {
                $rules = $this->rule_model->field('id')->select();
                if ($rules) {
                    foreach ($rules as $k => $v) {
                        if ($v['id'] > 0) {
                            $auth_list[] = $v['id'];
                        }
                    }
                }

            } else {
                //获取用户所属的组
                $groups = $this->user_model->groups()->where(['user_id' => $user_id])->select();
                if ($groups) {
                    foreach ($groups as $k => $v) {
                        if ($v['group_id'] > 0) {
                            $condition = [];
                            $condition['id'] = $v['group_id'];
                            $condition['status'] = 0;
                            $rule = $this->group_model->where($condition)->field('rules')->find();
                            if ($rule) {
                                $rule_arr = @explode(",", $rule['rules']);
                                if ($rule_arr) {
                                    foreach ($rule_arr as $rk => $rv) {
                                        if ($rv > 0 && !in_array($rv, $auth_list)) {
                                            //检查该权限是否又被禁用
                                            $condition = [];
                                            $condition['id'] = $rv;
                                            $condition['status'] = 0;//0,有效
                                            $rule_rs = $this->rule_model->where($condition)->field('id,pid')->find();
                                            if ($rule_rs) {
                                                if ($rule_rs['pid'] > 0) {
                                                    //查询父节点
                                                    $condition = [];
                                                    $condition['id'] = $rule_rs['pid'];
                                                    $condition['status'] = 0;//0,有效
                                                    if ($this->rule_model->where($condition)->field('id')->find()) {
                                                        $auth_list[] = $rv;
                                                    }
                                                } else {
                                                    $auth_list[] = $rv;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            session('auth_list', $auth_list);
        }

        return ($auth_list);
    }

    /**
     * @describe 权限分配页面
     * @return mixed
     */
    public function access()
    {
        $this->auth();
        $id = $this->request->get('id');
        $builder = new AdminAccessBuilder();
        $builder->title('权限')->suggest('权限设置')->setSaveUrl(url('admin/auth/updateOfAuth'))->setGroupId($id);
        $rules = Group::get($id);
        if ($rules['status'] == 1) {
            $this->send(0, "该角色已被禁用");
        }
        $builder->data($rules['rules']);
        //写日志
        Log::writeLog("进入权限分配页面");
        return $builder->displayAccess();
    }

    /**
     * 分配权限
     * @return \think\response\Json
     */
    public function updateOfAuth()
    {
        $this->auth();
        $rule_ids = trim(input('checks'));
        $group_id = trim(input('group_id'));
        $rules = "";
        $temp_arr = [];
        if ($group_id > 0) {
            //判断该角色是否已被禁用
            $group_rs = $this->group_model->field('status')->find();
            if ($group_rs) {
                if ($group_rs['status'] == 1) {
                    return $this->send(0, '该角色已被禁用');
                }
            } else {
                return $this->send(0, '该角色异常');
            }


            if ($rule_ids) {
                $rules_arr = @explode(",", $rule_ids);
                if ($rules_arr) {
                    foreach ($rules_arr as $k => $v) {
                        if ($v > 0) {
                            $temp_arr[] = $v;
                        }
                    }
                }
                $rules = @implode(',', @array_flip(array_flip($temp_arr)));
            }

            if ($this->group_model->where(["id" => $group_id])->update(['rules' => $rules])) {
                return $this->send(1, lang('OPERATE_SUCCESS'), url('admin/group/groupList'));
            }

        }
        //写日志
        Log::writeLog("分配权限");
        return $this->send(0, lang('OPERATE_FAILE'));
    }

    /**
     * @return mixed
     */
    public function login()
    {
        if ($this->request->isPost()) {
            //提交
            $account = trim($this->request->post('account'));
            $password = trim(input("password"));
            if (!$account || !$password) {
                $this->result([], 1, "账号或密码错误", 'json');
            }
            $condition = [];
            $condition['account'] = $account;
            $condition['password'] = md5($password);
            $rs = $this->user_model->where($condition)->field('id,nickname,account,avatar,status')->find();
            if ($rs) {
                //1：禁用 0：启用
                if ($rs['status'] == 0) {
                    //登陆成功

                    session('user_id', $rs['id']);
                    session('nickname', $rs['nickname']);
                    session('account', $rs['account']);

                    cookie('user_avatar', qiniuUrl($rs['avatar']));
                    cookie('account', $rs['account']);
                    cookie('gatway_key', md5($rs['id']), $this->no_action_time);

                    //写日志
                    Log::writeLog("登陆成功");
                    $this->result([], 0, "登陆成功", 'json');
                } else {
                    $this->result([], 1, "账户已被禁用", 'json');
                }

            } else {
                $this->result([], 1, "账号或密码错误", 'json');
            }

        } else {
            //渲染
            return $this->fetch("/Auth/login");
        }
    }

    /**
     * @return mixed
     */
    public function logout()
    {
        //清除session
        //写日志
        Log::writeLog("退出系统");
        Session::clear();
        //跳转到登陆界面
        return $this->login();

    }

}